from dataclasses import dataclass
from datetime import date
from email.policy import default
from pdb import pm
from pickle import NONE
from time import time
from flask import Flask, jsonify, render_template, request, request_started
from jinja2 import Undefined
from matplotlib.font_manager import json_dump
from matplotlib.pyplot import draw_if_interactive, flag
from sklearn.manifold import MDS
from sklearn.cluster import AgglomerativeClustering
import numpy as np
import pandas as pd
import json
import os
from scipy.cluster.hierarchy import dendrogram


# 月份天数
def f(y, m):
    y = int(y)
    m = int(m)-1
    a = 0
    if ((y % 4 == 0 and y % 100 != 0) or y % 400 == 0) and m == 1:
        a = 1
    da = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return da[m]+a


# 日期转字符串
def toDay(d):
    if(d < 10):
        return '0'+str(d)
    else:
        return str(d)


# hourly data for the map's color reflection
def getMapHour(year, month, day, hour):
    retVal = {}
    with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as fp:
        ori = json.load(fp)
        for i in range(0, len(sitesNum)):
            if ori[str(hour)].get(sitesNum[i]) != None:
                retVal[sitesNum[i]] = ori[str(hour)][sitesNum[i]][0]
    return retVal


# daily data for the map's color reflection
def getMapDay(year, month, day):
    retVal = {}
    with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as fp:
        ori = json.load(fp)
        for i in range(0, len(sitesNum)):
            temp = [0, 0]
            for j in range(0, 24):
                tempOri = ori[str(j)]
                if tempOri.get(sitesNum[i]) != None:
                    temp[0] += tempOri[sitesNum[i]][0]
                    temp[1] += 1
            if temp[1] != 0:
                retVal[sitesNum[i]] = temp[0] / temp[1]
    return retVal


# monthly data for the map's color reflection
def getMapMonth(year, month):
    retVal = {}
    sites = ['1223A', '1224A', '1226A', '1227A', '1228A', '1229A', '1230A',
             '1231A', '1232A', '1233A', '2010A', '2011A', '2012A', '2013A']
    with open('./static/colorReflection/' + year + '/' + year + '' + month + '.json', 'r', encoding='utf8') as fp:
        ori = json.load(fp)
        for site in sites:
            retVal[site] = ori[site]
    return retVal


# yearly data for the map's color reflection
def getMapYear(year):
    retVal = {}
    sites = ['1223A', '1224A', '1226A', '1227A', '1228A', '1229A', '1230A',
             '1231A', '1232A', '1233A', '2010A', '2011A', '2012A', '2013A']
    with open('./static/colorReflection/' + year + '/' + year + '.json', 'r', encoding='utf8') as fp:
        ori = json.load(fp)
        for site in sites:
            retVal[site] = ori[site]
    return retVal


# arcHour 小时AQI平均
def getArcHour(year, month, day):
    with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as fp:
        hd = json.load(fp)
    hour = {}
    for i in range(0, 24):
        sum = 0
        _key = list(hd[str(i)].keys())
        for k in range(0, len(_key)):

            sum += hd[str(i)][_key[k]][0]
        if(len(_key) != 0):
            sum /= len(_key)
        else:
            sum = 0
        hour[str(i)] = sum
    return hour


# arcDay 每天AQI平均
def getArcDay(year, month):
    md = {}
    for day in range(0, f(year, month)):  # f(year,month)
        path = './static/data/' + year + '/' + year + \
            '' + month + '' + toDay(day+1) + '.json'
        if(not(os.path.exists(path))):
            continue
        with open('./static/data/' + year + '/' + year + '' + month + '' + toDay(day+1) + '.json', 'r', encoding='utf8') as fp:
            dd = json.load(fp)
          # print(dd)
        num = 0
        sum = 0
        for i in range(0, 24):
            sumtemp = 0
            _key = list(dd[str(i)].keys())
            for k in range(0, len(_key)):
                sumtemp += dd[str(i)][_key[k]][0]
            if(len(_key) != 0):
                sumtemp /= len(_key)
                num += 1
            else:
                sumtemp = 0
            # print(sumtemp)
            sum += sumtemp
        sum /= num
        md[str(day+1)] = sum
    return md


# arcMonth 每月AQI平均
def getArcMonth(year):
    with open('./static/data/arcMonthDate.json', 'r', encoding='utf8') as fp:
        yd = json.load(fp)[year]
    return yd


# arcWeek 一周每天AQI平均
def getArcWeek(year, month, day, week):
    week = int(week)-1
    day = int(day)
    day = day - week
    # print(day)
    md = {}
    for p in range(0, 7):
        # print(day)
        path = './static/data/' + year + '/' + year + \
            '' + month + '' + toDay(day) + '.json'
        if(not(os.path.exists(path))):
            md[str(p)] = 0
            day += 1
            continue
        with open(path, 'r', encoding='utf8') as fp:
            dd = json.load(fp)
          # print(dd)
        num = 0
        sum = 0
        for i in range(0, 24):
            sumtemp = 0
            _key = list(dd[str(i)].keys())
            for k in range(0, len(_key)):
                sumtemp += dd[str(i)][_key[k]][0]
            if(len(_key) != 0):
                sumtemp /= len(_key)
                num += 1
            else:
                sumtemp = 0
            # print(sumtemp)
            sum += sumtemp
        sum /= num
        md[str(p)] = sum
        day += 1
    return md


# 获取降维结果
def getMDS(sites, dim, date, hour, year):
    with open('./static/data/' + year + '/' + date + '.json', 'r', encoding='utf8') as f:
        data = json.load(f)
    input = []
    temp = []
    use_sites = []
    # poluIndex = ['aqi', 'pm25', 'pm25_24h', 'pm10', 'pm10_24h', 'so2', 'so2_24h',
    #             'no2', 'no2_24h', 'o3', 'o3_24h', 'o3_8h', 'o3_8h_24h', 'co', 'co_24h']
    for site in sites:
        if data[hour].get(site) == None:
            continue
        for index, d in enumerate(dim):
            if d == 'true':
                temp.append(data[hour][site][index])
        use_sites.append(site)
        input.append(temp)
        temp = []
    # print(input)
    # print(use_sites)

    embedding = MDS(n_components=2)
    res = embedding.fit_transform(input)
    return res, use_sites


# 构建层次对象
def appendChild(newNode, Nodes, Node, n, sav):
    level = {}
    level['name'] = str(Node)
    level['children'] = []
    if(Nodes[0] >= n):
        nNode = Nodes[0]
        nNodes = newNode[nNode - n]
        temp = appendChild(newNode, nNodes, nNode, n, sav)
        level['children'].append(temp)
    elif(Nodes[0] < n):
        level['children'].append(sav[Nodes[0]])

    if(Nodes[1] >= n):
        nNode = Nodes[1]
        nNodes = newNode[nNode - n]
        temp = appendChild(newNode, nNodes, nNode, n, sav)
        level['children'].append(temp)
    elif(Nodes[1] < n):
        level['children'].append(sav[Nodes[1]])
    return level


# 获取层次聚类的层次等级
def getLevel(model, year, month, day, hour, sites):
    counts = np.zeros(model.children_.shape[0])
    n_samples = len(model.labels_)
    newNode = []
    for i, merge in enumerate(model.children_):
        current_count = 0
        for child_idx in merge:
            if child_idx < n_samples:
                current_count += 1
            else:
                current_count += counts[child_idx - n_samples]
        counts[i] = current_count
    Z = np.column_stack([model.children_, model.distances_, counts])
    Z = list(Z)
    for i in range(0, n_samples - 1):
        newNode.append([int(Z[i][0]), int(Z[i][1])])

    savYear = []
    savMonth = []
    savDay = []
    savHour = {
        '0': [],
        '1': [],
        '2': [],
        '3': [],
        '4': [],
        '5': [],
        '6': [],
        '7': [],
        '8': [],
        '9': [],
        '10': [],
        '11': [],
        '12': [],
        '13': [],
        '14': [],
    }
    for i in range(0, n_samples):
        for k in range(0, 15):
            # # 拿取点位年数据对象
            # with open('./static/colorReflection/' + year + '/' + year + '.json', 'r', encoding='utf8') as f:
            #     data = json.load(f)
            #     for j in range(0, len(sites)):
            #         savYear.append({
            #             "name": sites[j],
            #             "value": data[sites[j]]
            #         })
            # # 拿取点位月数据对象
            # with open('./static/colorReflection/' + year + '/' + year + '' + month + '.json', 'r', encoding='utf8') as f:
            #     data = json.load(f)
            #     for j in range(0, len(sites)):
            #         savMonth.append({
            #             "name": sites[j],
            #             "value": data[sites[j]]
            #         })
            # # 拿取点位日数据对象
            # with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as f:
            #     data = json.load(f)
            #     for j in range(0, len(sites)):
            #         array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            #         for k in range(0, 24):
            #             if(data[str(k)].get(sites[j]) != None):
            #                 array[0] += data[str(k)][sites[j]][0]
            #                 array[1] += data[str(k)][sites[j]][1]
            #                 array[2] += data[str(k)][sites[j]][2]
            #                 array[3] += data[str(k)][sites[j]][3]
            #                 array[4] += data[str(k)][sites[j]][4]
            #                 array[5] += data[str(k)][sites[j]][5]
            #                 array[6] += data[str(k)][sites[j]][6]
            #                 array[7] += data[str(k)][sites[j]][7]
            #                 array[8] += data[str(k)][sites[j]][8]
            #                 array[9] += data[str(k)][sites[j]][9]
            #                 array[10] += data[str(k)][sites[j]][10]
            #                 array[11] += data[str(k)][sites[j]][11]
            #                 array[12] += data[str(k)][sites[j]][12]
            #                 array[13] += data[str(k)][sites[j]][13]
            #                 array[14] += data[str(k)][sites[j]][14]
            #                 array[15] += 1
            #         temp = [
            #             array[0] / array[15], array[1] / array[15], array[2] / array[15], array[3] / array[15], array[4] / array[15],
            #             array[5] / array[15], array[6] / array[15], array[7] / array[15], array[8] / array[15], array[9] / array[15],
            #             array[10] / array[15], array[11] / array[15], array[12] / array[15], array[13] / array[15], array[14] / array[15]
            #         ]
            #         savDay.append({
            #             "name": sites[j],
            #             "value": temp
            #         })
            # 拿取点位小时数据对象
            with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as f:
                data = json.load(f)
                for j in range(0, len(sites)):
                    savHour[str(k)].append({
                        "name": sites[j],
                        "value": data[str(hour)][sites[j]][k]
                    })

    Nodes = newNode[len(newNode) - 1]
    Node = len(newNode) - 1 + n_samples
    level = {}
    # level['levelYear'] = appendChild(newNode, Nodes, Node, n_samples, savYear)
    # level['levelMonth'] = appendChild(newNode, Nodes, Node, n_samples, savMonth)
    # level['levelDay'] = appendChild(newNode, Nodes, Node, n_samples, savDay)
    print(newNode)
    level['levelHour0'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['0'])
    level['levelHour1'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['1'])
    level['levelHour2'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['2'])
    level['levelHour3'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['3'])
    level['levelHour4'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['4'])
    level['levelHour5'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['5'])
    level['levelHour6'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['6'])
    level['levelHour7'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['7'])
    level['levelHour8'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['8'])
    level['levelHour9'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['9'])
    level['levelHour10'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['10'])
    level['levelHour11'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['11'])
    level['levelHour12'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['12'])
    level['levelHour13'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['13'])
    level['levelHour14'] = appendChild(
        newNode, Nodes, Node, len(newNode) + 1, savHour['14'])

    return level


# 返回聚类的结果
def hierarchical(sites, dim, date, hour, year, threshold):
    with open('./static/data/' + year + '/' + date + '.json', 'r', encoding='utf8') as f:
        data = json.load(f)
    input = []
    temp = []
    use_sites = []
    # poluIndex = ['aqi', 'pm25', 'pm25_24h', 'pm10', 'pm10_24h', 'so2', 'so2_24h',
    #             'no2', 'no2_24h', 'o3', 'o3_24h', 'o3_8h', 'o3_8h_24h', 'co', 'co_24h']
    for site in sites:
        if data[hour].get(site) == None:
            continue
        for index, d in enumerate(dim):
            if d == 'true':
                temp.append(data[hour][site][index])
        use_sites.append(site)
        input.append(temp)
        temp = []
    # print(input)
    # print(use_sites)

    threshold = int(threshold)

    clustering = AgglomerativeClustering(
        linkage='ward', distance_threshold=threshold, n_clusters=None)
    clustering = clustering.fit(input)

    # month = date[4:6]
    # day = date[6:8]

    # 获取层次结构
    # level = getLevel(clustering, year, month, day, hour, sites)

    # clustering.labels_返回的是一个标签的列表，与use_sites里的站点的顺序一一对应
    # print(clustering.labels_)
    res = clustering.labels_

    return res


# 返回层次聚类层次
def hierarchicalL(sites, dim, date, hour, year, threshold):
    with open('./static/data/' + year + '/' + date + '.json', 'r', encoding='utf8') as f:
        data = json.load(f)
    input = []
    temp = []
    use_sites = []
    # poluIndex = ['aqi', 'pm25', 'pm25_24h', 'pm10', 'pm10_24h', 'so2', 'so2_24h',
    #             'no2', 'no2_24h', 'o3', 'o3_24h', 'o3_8h', 'o3_8h_24h', 'co', 'co_24h']
    for site in sites:
        if data[hour].get(site) == None:
            continue
        for index, d in enumerate(dim):
            if d == 'true':
                temp.append(data[hour][site][index])
        use_sites.append(site)
        input.append(temp)
        temp = []
    # print(input)
    # print(use_sites)

    threshold = int(threshold)

    clustering = AgglomerativeClustering(
        linkage='ward', distance_threshold=threshold, n_clusters=None)
    clustering = clustering.fit(input)

    month = date[4:6]
    day = date[6:8]

    # 获取层次结构
    level = getLevel(clustering, year, month, day, hour, sites)

    return level

# Timedata_hour


def getHourTime(year, month, day, sites):
    with open('./static/data/' + year + '/' + year + '' + month + '' + day + '.json', 'r', encoding='utf8') as fp:
        hd = json.load(fp)
    data = {}
    for i in range(0, 24):
        _key = _key = list(hd[str(i)].keys())
        data[i] = []
        for k in range(0, len(sites)):
            if sites[k] in _key:
                data[i].append(hd[str(i)][sites[k]][0])
            else:
                data[i].append(0)
    timeData = {}
    for k in range(0, len(sites)):
        timeData[sites[k]] = timeSort(k, data, 0, 24)
    return timeData

# Timedata_day


def getDayTime(year, month, sites):
    data = {}

    for day in range(0, f(year, month)):  # f(year,month)
        sumtemp = [0 for i in range(len(sites))]
        numtemp = [0 for i in range(len(sites))]
        path = './static/data/' + year + '/' + year + \
            '' + month + '' + toDay(day+1) + '.json'
        if(not(os.path.exists(path))):
            data[day] = sumtemp
            continue
        with open(path, 'r', encoding='utf8') as fp:
            dd = json.load(fp)
        # print(dd)

        for h in range(0, 24):
            _key = list(dd[str(h)].keys())

            for k in range(0, len(sites)):
                if sites[k] in _key:
                    sumtemp[k] += dd[str(h)][sites[k]][0]
                    numtemp[k] += 1
                else:
                    sumtemp[k] += 0
                    numtemp[k] += 1

        for k in range(0, len(sites)):
            sumtemp[k] /= numtemp[k]

        data[day] = sumtemp
    timeData = {}
    for k in range(0, len(sites)):
        timeData[sites[k]] = timeSort(k, data, 0, f(year, month))
    return timeData

# Timedata_week


def getWeekTime(year, month, day, week, sites):
    week = int(week)-1
    day = int(day)
    day = day - week
    # print(day)
    data = {}

    for p in range(0, 7):
        # print(day)
        sumtemp = [0 for i in range(len(sites))]
        numtemp = [0 for i in range(len(sites))]
        path = './static/data/' + year + '/' + year + \
            '' + month + '' + toDay(day) + '.json'
        if(not(os.path.exists(path))):
            data[p] = sumtemp
            day += 1
            continue
        with open(path, 'r', encoding='utf8') as fp:
            dd = json.load(fp)
          # print(dd)

        for h in range(0, 24):
            _key = list(dd[str(h)].keys())

            for k in range(0, len(sites)):
                if sites[k] in _key:
                    sumtemp[k] += dd[str(h)][sites[k]][0]
                    numtemp[k] += 1
                else:
                    sumtemp[k] += 0
                    numtemp[k] += 1

        for k in range(0, len(sites)):
            sumtemp[k] /= numtemp[k]
        data[p] = sumtemp
    timeData = {}
    for k in range(0, len(sites)):
        timeData[sites[k]] = timeSort(k, data, 0, 7)
    return timeData

# Timedata_month


def getMonthTime(year, sites):
    temp = {'1223A': 0,
            '1224A': 1,
            '1226A': 2,
            '1227A': 3,
            '1228A': 4,
            '1229A': 5,
            '1230A': 6,
            '1231A': 7,
            '1232A': 8,
            '1233A': 9,
            '2010A': 10,
            '2011A': 11,
            '2012A': 12,
            '2013A': 13}
    with open("./static/data/yearTimeData.json", 'r', encoding='utf8') as fp:
        dd = json.load(fp)
        # print(dd[year])

    data = {}
    # for k in range(0, len(sites)):
    #     data[sites[k]] = []
    for i in range(0, 12):
        data[i] = []
        for k in range(0, len(sites)):
            data[i].append(dd[year][str(i)][temp[sites[k]]])

    # print(data)
    timeData = {}
    for k in range(0, len(sites)):
        timeData[sites[k]] = timeSort(k, data, 0, 12)
    return timeData

# timedata等级划分和排名处理  / 站点：{时间：[原数据，总排名，AQI等级，等级内排名]}  /


def timeSort(site, data, start, type):
    AQI = [0, 1, 2, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5]
    temp = {}
    for i in range(0, start):
        temp[i] = [0, 0, 0, 0]
    for i in range(start, type):
        arr = 0
        sameArr = 0
        for j in range(0, len(data[i])):
            if(data[i][site] < data[i][j]):
                arr += 1
                if(int(data[i][site]/50) == int(data[i][j]/50)):
                    sameArr += 1
        temp[i] = [data[i][site], arr, sameArr, int(data[i][site]/50)]
    return temp


app = Flask(__name__)


sitesNum = []
with open('./static/sites.json', 'r', encoding='utf8') as fp:
    sites = json.load(fp)
    for i in range(0, len(sites)):
        sitesNum.append(sites[i]["content"][0:5])
# print(sitesNum)


@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


@app.route('/')
def index():
    return render_template('index.html')


@app.route("/getData")
def test():
    data = {
        "arcMonth": '',
        "arcDay": '',
        "arcWeek": '',
        "arcHour": '',
    }
    # 拿取相关量
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    hour = request.args.get('hour')
    week = request.args.get('week')
    # print(int(week)-1)
    print(year, month, day, hour, week, 'lxm')
    # 获取数据并且加入返回数据数组
    arcHour = getArcHour(year, month, day)
    arcDay = getArcDay(year, month)
    arcMonth = getArcMonth(year)
    arcWeek = getArcWeek(year, month, day, week)

    data['arcMonth'] = arcMonth
    data['arcDay'] = arcDay
    data['arcWeek'] = arcWeek
    data['arcHour'] = arcHour

    return json.dumps(data)


@app.route("/getTime")
def getTimeData():
    sites = []
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    hour = request.args.get('hour')
    week = request.args.get('week')
    leng = request.args.get('leng')
    for i in range(0, int(leng)):
        temp = request.args.get(str(i))
        sites.append(temp)

    # print(sites, year, 'lxm')
    h_data = getHourTime(year, month, day, sites)
    d_data = getDayTime(year, month, sites)
    w_data = getWeekTime(year, month, day, week, sites)
    m_data = getMonthTime(year, sites)
    data = {
        "day": d_data,
        "hour": h_data,
        "week": w_data,
        "month": m_data,
    }
    # print(data)
    return json.dumps(data)


@app.route("/getMapData")
def getMapData():
    data = {
        "year": '',
        "month": '',
        "day": '',
        "hour": ''
    }
    # 拿取相关量
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    hour = request.args.get('hour')

    # 获取数据并且加入返回数据数组
    mapHour = getMapHour(year, month, day, hour)
    mapDay = getMapDay(year, month, day)
    mapMonth = getMapMonth(year, month)
    mapYear = getMapYear(year)

    data['hour'] = mapHour
    data['day'] = mapDay
    data['month'] = mapMonth
    data['year'] = mapYear

    return json.dumps(data)


@app.route("/MDSaFCLU")
def flex():
    # 返回的数据
    data = {
        "MDS": '',
        "use_sites": '',
    }
    # 选中的站点
    sites = []
    # 降维所用维度
    dim = []
    # 选择的日期
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    date = year + month + day
    # 选择的时刻
    hour = request.args.get('hour')
    # print(date)

    leng = request.args.get('leng')

    for i in range(0, int(leng)):
        temp = request.args.get(str(i))
        sites.append(temp)

    # 确定降维所用量存入数组
    dim.append(request.args.get('aqi'))
    dim.append(request.args.get('pm25'))
    dim.append(request.args.get('pm25_24h'))
    dim.append(request.args.get('pm10'))
    dim.append(request.args.get('pm10_24h'))
    dim.append(request.args.get('so2'))
    dim.append(request.args.get('so2_24h'))
    dim.append(request.args.get('no2'))
    dim.append(request.args.get('no2_24h'))
    dim.append(request.args.get('o3'))
    dim.append(request.args.get('o3_24h'))
    dim.append(request.args.get('o3_8h'))
    dim.append(request.args.get('o3_8h_24h'))
    dim.append(request.args.get('co'))
    dim.append(request.args.get('co_24h'))

    # print(leng, sites, dim)

    data['MDS'], data['use_sites'] = getMDS(sites, dim, date, hour, year)
    data['MDS'] = data['MDS'].tolist()

    # print(data)
    return json.dumps(data)


@app.route("/hier")
def hier():
    # 返回的数据
    data = {
        "hier": '',
        # "use_sites": '',
    }
    # 选中的站点
    sites = []
    # 降维所用维度
    dim = []
    # 选择的日期
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    date = year + month + day
    # 选择的时刻
    hour = request.args.get('hour')
    # print(date)
    leng = request.args.get('leng')
    # 阈值
    threshold = request.args.get('threshold')

    for i in range(0, int(leng)):
        temp = request.args.get(str(i))
        sites.append(temp)

    # 确定降维所用量存入数组
    dim.append(request.args.get('aqi'))
    dim.append(request.args.get('pm25'))
    dim.append(request.args.get('pm25_24h'))
    dim.append(request.args.get('pm10'))
    dim.append(request.args.get('pm10_24h'))
    dim.append(request.args.get('so2'))
    dim.append(request.args.get('so2_24h'))
    dim.append(request.args.get('no2'))
    dim.append(request.args.get('no2_24h'))
    dim.append(request.args.get('o3'))
    dim.append(request.args.get('o3_24h'))
    dim.append(request.args.get('o3_8h'))
    dim.append(request.args.get('o3_8h_24h'))
    dim.append(request.args.get('co'))
    dim.append(request.args.get('co_24h'))

    # print(leng, sites, dim)

    data['hier'] = hierarchical(sites, dim, date, hour, year, threshold)
    data['hier'] = data['hier'].tolist()

    # print(data)
    return json.dumps(data)


@app.route("/getTreeLevel")
def getTreeLevel():
    # 返回的数据
    data = {
        "level": '',
    }
    # 选中的站点
    sites = []
    # 降维所用维度
    dim = []
    # 选择的日期
    year = request.args.get('year')
    month = request.args.get('month')
    day = request.args.get('day')
    date = year + month + day
    # 选择的时刻
    hour = request.args.get('hour')
    # print(date)
    leng = request.args.get('leng')
    # 阈值
    threshold = request.args.get('threshold')

    for i in range(0, int(leng)):
        temp = request.args.get(str(i))
        sites.append(temp)

    # 确定降维所用量存入数组
    dim.append(request.args.get('aqi'))
    dim.append(request.args.get('pm25'))
    dim.append(request.args.get('pm25_24h'))
    dim.append(request.args.get('pm10'))
    dim.append(request.args.get('pm10_24h'))
    dim.append(request.args.get('so2'))
    dim.append(request.args.get('so2_24h'))
    dim.append(request.args.get('no2'))
    dim.append(request.args.get('no2_24h'))
    dim.append(request.args.get('o3'))
    dim.append(request.args.get('o3_24h'))
    dim.append(request.args.get('o3_8h'))
    dim.append(request.args.get('o3_8h_24h'))
    dim.append(request.args.get('co'))
    dim.append(request.args.get('co_24h'))

    # print(leng, sites, dim)

    data['level'] = hierarchicalL(sites, dim, date, hour, year, threshold)

    # print(data)
    return json.dumps(data)


if __name__ == '__main__':
    app.run(debug=True)
